import { Component, Inject, OnInit } from '@angular/core';
import { DatePipe } from '@angular/common';
import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material';
import { TranslateService } from '@ngx-translate/core';
import { RestService } from '../../services/rest.service';
import { Angular5Csv } from 'angular5-csv/Angular5-csv';

@Component({
  selector: 'app-export-alarm-dialog',
  templateUrl: './export-alarm-dialog.component.html',
  styleUrls: ['./export-alarm-dialog.component.css']
})
export class ExportAlarmDialogComponent implements OnInit {
  params: any;
  url: string;
  alarms: any[];
  percentage = 0;
  percentTips = '';

  constructor(@Inject(MAT_DIALOG_DATA) private dialogData: any,
              public dialogRef: MatDialogRef<ExportAlarmDialogComponent>,
              public rest: RestService,
              private datePipe: DatePipe,
              private translate: TranslateService) {
    this.params = dialogData.params;
    this.url = dialogData.url;
  }

  getNextPage(href) {
    const index = href.indexOf('data/alarm/search/');
    href = href.substring(index);
    this.rest.get(href).subscribe(resp => {
      this.processAlarms(resp['_embedded']['alarms']);
      this.percentTips = this.alarms.length + '/' + resp['page']['totalElements'];
      this.percentage = Math.round(this.alarms.length * 100 / resp['page']['totalElements']);
      const nextUrl = resp['_links']['next'];
      if (nextUrl && nextUrl.href) {
        this.getNextPage(nextUrl.href);
      } else {
        this.save2file();
      }
    }, message => {
      console.error('Failed to export alarms from server!');
      this.save2file();
    });
  }

  save2file() {
    this.dialogRef.close('');
    let fileName = 'alarmsFrom[';
    fileName += (this.params['startTime'] ? this.datePipe.transform(this.params['startTime'], 'yyyyMMddHHmmss') : '-') + ']To[';
    fileName += (this.params['endTime'] ? this.datePipe.transform(this.params['endTime'], 'yyyyMMddHHmmss') : '-') + ']Person[';
    fileName += (this.params['personName'] ? this.params['personName'] : '-') + ']';
    fileName += this.datePipe.transform(new Date(), 'yyyyMMddHHmmss');
    new Angular5Csv(this.alarms, fileName, {
      headers: [
        this.translate.get('raisedTime')['value'],
        this.translate.get('alarmType')['value'],
        this.translate.get('ackedTime')['value'],
        this.translate.get('personName')['value'],
        this.translate.get('deviceId')['value']
      ]
    });
  }

  processAlarms(input) {
    input.forEach(alarm => {
      this.alarms.push({
        raisedTime: alarm.raisedTime === 0 ? '-' : this.datePipe.transform(alarm.raisedTime, 'yyyy-MM-dd HH:mm:ss'),
        type: this.translate.get(alarm.type)['value'],
        ackedTime: alarm.ackedTime === 0 ? '-' : this.datePipe.transform(alarm.ackedTime, 'yyyy-MM-dd HH:mm:ss'),
        personName: alarm.personName,
        deviceId: alarm.deviceId
      });
    });
  }

  ngOnInit() {
    this.alarms = [];
    this.rest.getWithParams(this.url, this.params).subscribe(resp => {
      console.info('got alarms');
      this.processAlarms(resp['_embedded']['alarms']);
      this.percentTips = this.alarms.length + '/' + resp['page']['totalElements'];
      this.percentage = Math.round(this.alarms.length * 100 / resp['page']['totalElements']);
      const nextUrl = resp['_links']['next'];
      if (nextUrl && nextUrl.href) {
        this.getNextPage(nextUrl.href);
      } else {
        this.save2file();
      }
    }, message => {
      console.error('Failed to export alarms from server!');
      this.save2file();
    });
  }
}